package com.easyfun.healthmagicbox.comm;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

import android.content.Context;
import android.util.Log;

import com.easyfun.healthmagicbox.base.DatabaseAccess;
import com.easyfun.healthmagicbox.base.DatabaseAccessImplementation;
import com.easyfun.healthmagicbox.ormlite.DatabaseHelper;
import com.easyfun.healthmagicbox.ormlite.ServerResponseCode;
import com.easyfun.healthmagicbox.comm.json.DoctorProfileJsonWrapper;
import com.easyfun.healthmagicbox.comm.json.DoctorProfileListJsonWrapper;
import com.easyfun.healthmagicbox.pojo.ConstantData;
import com.easyfun.healthmagicbox.pojo.DoctorProfile;
import com.easyfun.healthmagicbox.pojo.PersonProfile;
import com.easyfun.healthmagicbox.sync.CommCallback;
import com.j256.ormlite.dao.Dao;

public class DoctorProfileDownloadTask  extends BaseCommTask implements Runnable,
	DatabaseAccess {
	private final static String LOG_TAG = DoctorProfileDownloadTask.class.getSimpleName();
	String mdoctorID;

	public DoctorProfileDownloadTask(String doctorID,Context context, 
			CommCallback callback) {

		super(context,callback);
		mdoctorID = doctorID;
	}
	@Override
	public DatabaseHelper getHelper(Context context) {
		return DatabaseAccessImplementation.getInstance().getHelper(mcontext);
	}

	@Override
	public void run() {
		JSONObject serializedObj = new JSONObject();
		String result = "";
		try {
			serializedObj.put("doctorID", mdoctorID);

			Map<String, String> parmas = new HashMap<String, String>();
			parmas.put("jsonstring", serializedObj.toString());
			result = super.uploadByHTTP(parmas, ConstantData.DoctorProfileDownloadURI);
			if (ServerResponseCode.parseOf(result) == ServerResponseCode.FAILED) {

				ccb.setCommResult(this, result,
						ServerResponseCode.FAILED);
				return;
			}

			if ((result.length() > 0)) {
				if (ServerResponseCode.parseOf(result) == ServerResponseCode.SUCCESS) {
					ccb.setCommResult(this, result,
							ServerResponseCode.SUCCESS);
				} else {
					Dao<DoctorProfile, Integer> ppdao = getHelper(mcontext)
							.getDoctorProfileDao();
					List<DoctorProfile> datas =  
							DoctorProfileListJsonWrapper
							.getInstance(result,DoctorProfileListJsonWrapper.class).getMpps();

					for (DoctorProfile data:datas)
					{
						List<DoctorProfile> oldpp = ppdao.queryBuilder().where().eq("doctorID", data.getDoctorID())
							.query();
						if (oldpp.size()>0)
						{
							ppdao.deleteById(oldpp.get(0).getId());
						}
						ppdao.create(data);
					}
					ccb.setCommResult(this, result,
							ServerResponseCode.SUCCESS);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			Log.e(LOG_TAG, e.toString());
			ccb.setCommResult(this, result,
					ServerResponseCode.FAILED);
		}
		
		
	}

}
